<template>
  <view class="container" :style="{backgroundImage:'url('+auth_bg+')'}"
    style="background-size: cover;background-position: center;display: flex;flex-direction: column;align-items: center;justify-content: center;">
    <view style="display: none;" class="fixed-right-tip" @click="backToExchange" v-if="navGoBack">
      跳过
      <!-- <u-icon color="#7E3508" size="24rpx" name="arrow-right"></u-icon> -->
    </view>
    <view class="center-box">
      <view class="center-title">万心测心理</view>
      <view class="cb-content-box">
        <image :src="auth_logo" class="ccb-logo" mode=""></image>
        <input type="number" placeholder="请输入手机号" class="ccb-phone" style="margin-top: 30rpx;" v-model="formData.phone">
        <view class="ccb-code-box">
          <input type="text" placeholder="请输入验证码" class="ccb-code-input" maxlength="6" v-model="formData.code">
          <view class="ccb-code" @click="$u.debounce(getPushCode,500)">{{codeText}}</view>
        </view>

        <view class="ccb-btn-login" :style="{opacity: formData.phone&&formData.code&&isAgree?1:0.3}">
          <image :src="auth_login_btn" mode=""></image>
          <button v-if="privacySetting.needAuthorization" id="agree-btn" class="ccb-btn-login-position"
            open-type="agreePrivacyAuthorization" @agreeprivacyauthorization="handleAgree"></button>
          <button v-else class="ccb-btn-login-position" @click="handleAgree"></button>
        </view>
        <view style="padding: 30rpx;box-sizing: border-box;font-size: 26rpx;">
          <checkbox-group @change="agreeChange" style="color: #999;font-size: 24rpx;">
            <checkbox value="agree" color="#248C61" style="transform:scale(0.7);" />勾选表示您已阅读并同意<span
              @click="goUserService('service')" style="color: #248C61;">{{privacySetting.privacyContractName}}</span>
          </checkbox-group>
        </view>
      </view>
      <view class="bottom-dianzhui"></view>
    </view>
  </view>
</template>

<script>
  import {
    verifyMobileNumber,
    sendVerificationCode
  } from '@/common/api/user_api.js'
  
  import {
  	submitEvaluate
  } from '@/common/api/order.js'
  export default {
    data() {
      return {
        auth_login_btn: this.imgBaseURL + '/auth/auth_login_btn.png',
        auth_logo: this.imgBaseURL + '/auth/auth_logo_psychology.png',
        auth_bg: this.imgBaseURL + '/auth/auth_bg.png', //背景图片
        fullPageBg: this.imgBaseURL + '/scl/result/fanhuaMBTI/do-question-bg.png',
        setInval: null,
        codeText: '发送验证码',
        time: 60,
        formData: {
          phone: '',
          code: '',
          miniCode: ''
        },
        isAgree: false,
        paramObj: null,
        privacySetting: {},
        loading: false,
        navGoBack:false
      }
    },
    onLoad(options) {
      console.log(this.$store,'====this.$store')
      console.log('options:', options)
      if (options.paramObj) {
        this.paramObj = JSON.parse(options.paramObj)
        if(this.paramObj && this.paramObj.isFullPage){
          this.auth_bg = this.fullPageBg
        }
        if(this.paramObj && this.paramObj.r == '5'){
          uni.setStorageSync('inviteId',this.paramObj.id)
        }
      }
      
      if(options.from && options.from == 'exchange'){
        this.navGoBack = true
      }
      
      let this_ = this;
      try {
        uni.getPrivacySetting({
          success: res => {
            this_.privacySetting = res;
            console.log(
              res
            ) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          },
          fail: () => {},
          complete: () => {}
        })
      } catch {
        this.privacySetting.privacyContractName = '《用户隐私保护指引》'
      }
    },
    methods: {
      backToExchange(){
        uni.redirectTo({
          url:'/subcontractorC/pages/exchangeGoods/exchangeGoods'
        })
      },
      handleAgree() {
        if(this.$fangBaoClick()){
          return
        }
        this.goLogin();
      },
      goLogin() {
        if (!this.isAgree) {
          this.$showToast('请勾选同意隐私保护指引')
          return
        }
        if (this.formData.phone == '' || this.formData.phone.length != 11) {
          this.$showToast('请输入正确的手机号')
          return
        }
        if (this.formData.code == '') {
          this.$showToast('请输入验证码')
          return
        }
        
        let this_ = this;
        uni.login({
          success(res) {
            console.log(res);
            this_.formData.miniCode = res.code;
            
            if (this_.paramObj && this_.paramObj.userType) {
              this_.formData.channelSource = this_.paramObj.userType;
            }
                  
            if(this_.$store.state.user.adType){
              this_.formData['adType'] = this_.$store.state.user.adType
            }
            const inviteId = uni.getStorageSync('inviteId')
            if (inviteId) {
              this_.formData['clientUserId'] = inviteId
            }
            
            // uni.showLoading({
            //   title:'加载中...'
            // })
            verifyMobileNumber(this_.formData).then(async res => {
              if (res.data.code == 200) {
                uni.setStorageSync('ttToken',res.data.data.token)
                await this_.$store.dispatch('user/getUserInfo')
                  
                let userInfo = Object.assign({},res.data.data.user);
                
                userInfo.hasRecptionCasePermission = userInfo.roles?.includes("storesSell");
                this_.$store.dispatch('app/getQrcodeInfo')
                uni.setStorageSync('balanceFlag', '1') //改变状态获取用户权益
                uni.setStorageSync('loginDate',this_.$dayjs().format('YYYY-MM-DD'))
                  
                this_.$store.commit('user/setUserInfo', userInfo)
                this_.$store.commit('user/setUserChannel', res.data.data.userChannel)
                
                
                if(this_.paramObj && this_.paramObj.isFullPage){
                  //从测评回答页进入的，再回到测评回答页要求用户支付
                  this_.paramObj.login = true
                  uni.redirectTo({
                    url:'/subcontractorD/pages/sclDoQuestion/sclDoQuestion?paramObj=' + JSON.stringify(this_.paramObj)
                  })
                }else if(this_.paramObj && this_.paramObj.userType=='evaluate'){
					submitEvaluate(this_.paramObj).then(resobj => {
						resobj = resobj.data
						if (resobj.code == 200) {
							uni.redirectTo({
								url: '/subcontractorC/pages/returnVisit/success?showScl='+this_.paramObj.showScl
							})
						} else {
							this_.$showToast(resobj.message)
						}
					})
					
				}else if(this_.navGoBack){
                  uni.redirectTo({
                    url:'/subcontractorC/pages/exchangeGoods/exchangeGoods'
                  })
                }else{
                  console.log('------uni.redirectTo-')
                  // 获取用户信息
                  uni.redirectTo({
                    url: '/subcontractorA/updateUserInfo/updateUserInfo?paramObj=' + JSON.stringify(this_
                      .paramObj)
                  })  
                } 
              } else {
                // 获取用户信息
                this_.$showToast(res.data.message);
              }
            }).finally(()=>{
              // uni.hideLoading()
            })
                  
            
            
            
            
          },
          fail() {
            this_.$showToast('登录失败')
          },
          complete() {
            
          }
        })
        
        
        
        
   
      
      },
      getPushCode() { //获取验证码
        if(this.$fangBaoClick())return
        if (this.formData.phone == '' || this.formData.phone.length != 11) {
          this.$showToast('请输入正确的手机号')
          return
        }
        if (this.time != 60) {
          return
        }
        this.time = 59;
        this.setCodeText()
        sendVerificationCode({
          phone: this.formData.phone
        }).then(res => {
          if (res.data.code != 200) {
            this.$showToast(res.data.message)
          }
        })
      },
      setCodeText() {
        if (this.setInval) {
          clearInterval(this.setInval)
        }
        this.setInval = setInterval(() => {
          this.time--;
          this.codeText = '重新获取(' + this.time + 's)'
          if (this.time == 0) {
            clearInterval(this.setInval)
            this.codeText = '发送验证码';
            this.time = 60;
          }
        }, 1000)
      },
      agreeChange(e) {
        let index = e.detail.value.findIndex((item) => item == 'agree')
        this.isAgree = index != -1;
      },
      goUserService(type) {
        try {
          uni.openPrivacyContract({
            success: () => {}, // 打开成功
            fail: () => {}, // 打开失败
            complete: () => {}
          })
        } catch {
          uni.navigateTo({
            url: '/subcontractorA/userPrivacyPolicy/userPrivacyPolicy'
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import url('authorization.css');
  
  .fixed-right-tip{
    
    column-gap: 14rpx;
  
    width: 120rpx;
    height: 50rpx;
    background: rgba(31, 134, 18, 1);
    border-radius: 33rpx;
    opacity: .7;
    position: fixed;
    right: 32rpx;
    top: 80rpx;
    z-index: 24;
    
   font-family: PingFangSC, PingFang SC;
   font-weight: 400;
   font-size: 30rpx;
   color: #FFFFFF;
   line-height: 50rpx;
   letter-spacing: 1px;
   text-align: center;
   font-style: normal;
  }
  
</style>